package components.utils
{
    import com.zn.bitmapDisplay.BitmapMovieClip;
    import components.core.MethodQueueElement;
    import components.core.UIComponent;
    import components.managers.SystemManager;
    
    import flash.display.Bitmap;
    import flash.display.DisplayObject;
    import flash.display.DisplayObjectContainer;
    import flash.display.Loader;
    import flash.display.MovieClip;
    
    import flashx.textLayout.elements.BreakElement;

    public class DestroyUtil
    {

		public static var cleanBitmapData:Boolean=true;
		
		public static function destroyChild(obj:Object):void
        {
            if (obj is DisplayObjectContainer &&
                !(obj is Loader))
            {
                var c:DisplayObjectContainer = obj as DisplayObjectContainer;
                var childObj:DisplayObject;
				var numChildren:int=0;

				if(c is MovieClip)
					(c as MovieClip).stop();
				
                while (c.numChildren > 0)
                {
					numChildren=c.numChildren;
					
                    childObj = c.removeChildAt(0);
					
					//判断是否为动画MC
					if(numChildren==c.numChildren)
						break;
					
                    if (childObj is UIComponent)
                        (childObj as UIComponent).destroy();
                    else
                        destroyChild(childObj);
                }
            }

            cleanChild(obj);
        }

        public static function cleanChild(obj:Object):void
        {
			var q:Array= UIComponent.methodQueue;
			for (var i:int = 0; i <q.length; i++)
			{
				var mqe:MethodQueueElement = q[i];
				if(mqe.obj==obj)
				{
					q.splice(i,1);
					break;
				}
			}
			
            EventListenerUtil.removeAllListenerFunc(obj);
            TimeoutIntervalUtil.removeObject(obj);

			if(cleanBitmapData)
			{
	            var bitmap:Bitmap = obj as Bitmap;
	            if (bitmap && bitmap.bitmapData)
	                bitmap.bitmapData.dispose();
			}
			
			if(obj is BitmapMovieClip)
				(obj as BitmapMovieClip).destroy();
			if(obj is UIComponent)
				(obj as UIComponent).destroy();
            if (obj is MovieClip)
                (obj as MovieClip).stop();

            if (SystemManager.rootStage.focus == obj)
                SystemManager.rootStage.focus = SystemManager.rootStage;
			if(obj is DisplayObject && (obj as DisplayObject).parent)
				(obj as DisplayObject).parent.removeChild(obj as DisplayObject);
        }
    }
}
